package com.wenjie.plugin.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

import com.wenjie.plugin.R;

import java.util.List;

/**
 * 系统服务，检测应用是否正在运行
 * 如果应用被异常退出，则重启应用
 */
public class SystemService extends Service {

    private static final String CHANNEL_ID = "HTTP_SERVER_CHANNEL_ID";
    private static final int SERVICE_ID = 1;

    private Thread autoThread;

    public SystemService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // 创建一个通知渠道
        String channelName = "自助终端服务";
        // 高优先级通知
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance);

        NotificationManager manager = getSystemService(NotificationManager.class);
        if (manager != null) {
            manager.createNotificationChannel(channel);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 启动前台服务
        startForegroundService();

        // 开启一个线程监控应用是否在运行
        autoThread =  new Thread(() -> {
            while (true) {
                // 检测应用是否运行
                if (!isAppRunning()) {
                    restartApp();
                }
                try {
                    Thread.sleep(3000); // 每3秒检查一次
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        if (!autoThread.isAlive()) {
            autoThread.start();
        }

        // 确保服务异常退出后能重启
        return START_STICKY;
    }

    /**
     * 启动前台服务
     */
    private void startForegroundService() {
        // 创建一个通知，显示服务正在运行
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("自助终端服务")
                .setContentText("服务正在运行")
                .setSmallIcon(R.drawable.service)
                .build();

        // 将服务设置为前台服务
        startForeground(SERVICE_ID, notification);
    }

    private boolean isAppRunning() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = activityManager.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            return topActivity != null && topActivity.getPackageName().equals(getPackageName());
        }

        return false;
    }

    private void restartApp() {
        Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}